// import {
//   areaList
// } from '@vant/area-data';
var util = require('../../utils/util')

Page({
  data: {
    // areaList,
    cateLoading: false,
    chooseShopCate: false,
    addressLoading: false,
    BussinessApplied: false,
    chooseAddress: false,
    pickerTypeShow: false,
    openTimeChoiceShow: false,
    fieldArr: [{
        id: 0,
        dataName: 'shop_name',
        value: '',
        label: '商家名称',
        placeholder: '请输入商家名称',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '30',
        errorMessage: '请输入商家名称',
        error: false,
        disabled: false,
      },
      {
        id: 1,
        dataName: 'linkman',
        value: '',
        label: '联系人',
        placeholder: '请输入联系人',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '10',
        errorMessage: '请输入联系人',
        error: false,
        disabled: false,
      },
      {
        id: 10,
        dataName: 'phone',
        value: '',
        label: '联系电话',
        placeholder: '请输入联系人电话号码',
        type: 'number',
        isLink: false,
        border: true,
        maxlength: '11',
        errorMessage: '请输入联系人电话号码',
        error: false,
        disabled: false,
      },
      {
        id: 11,
        dataName: 'shop_cate',
        value: '',
        label: '商家分类',
        placeholder: '请选择商家分类',
        type: 'text',
        isLink: true,
        border: true,
        maxlength: '10',
        errorMessage: '请选择商家分类',
        error: false,
        disabled: true,
      },
      {
        id: 2,
        dataName: 'shop_type',
        value: '',
        label: '结算类型',
        placeholder: '请选择结算类型',
        type: 'text',
        isLink: true,
        border: true,
        maxlength: '30',
        errorMessage: '请选择结算类型',
        error: false,
        disabled: true,
      },
      {
        id: 3,
        dataName: 'addressInfo',
        value: '',
        label: '店铺地址',
        placeholder: '请选择您的省市县',
        type: 'text',
        isLink: true,
        border: false,
        maxlength: '30',
        errorMessage: '请选择您的省市县',
        error: false,
        disabled: true,
      },
      {
        id: 12,
        dataName: 'contact_address',
        value: '',
        label: ' ',
        placeholder: '请选择您的详细地址',
        type: 'text',
        isLink: true,
        border: true,
        maxlength: '30',
        errorMessage: '请选择您的详细地址',
        error: false,
        disabled: true,
      },
      {
        id: 5,
        dataName: '',
        value: '',
        label: '上传图片',
        placeholder: '请按照要求上传图片',
        type: 'text',
        isLink: true,
        border: true,
        maxlength: '-1',
        errorMessage: '请按照要求上传图片',
        error: false,
        disabled: true,
      },
      {
        id: 6,
        dataName: 'shop_describe',
        value: '',
        label: '商家描述',
        placeholder: '请输入商家描述',
        type: 'textarea',
        isLink: false,
        border: true,
        maxlength: '255',
        errorMessage: '请输入商家描述',
        error: false,
        disabled: false,
      },
      {
        id: 9,
        dataName: '',
        value: '',
        label: '营业时间 ',
        placeholder: '请输入营业时间',
        type: 'text',
        isLink: true,
        border: true,
        maxlength: '40',
        errorMessage: '请输入营业时间',
        error: false,
        disabled: true,
      },
      {
        id: 7,
        dataName: 'shop_account',
        value: '',
        label: '登录账号',
        placeholder: '请输入登录账号',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '16',
        errorMessage: '账号须字母开头，5-16位字母和数字组合',
        error: false,
        disabled: false,
      },
      {
        id: 8,
        dataName: 'password',
        value: '',
        label: '登录密码',
        placeholder: '请输入登录密码',
        type: 'text',
        isLink: false,
        border: true,
        maxlength: '32',
        errorMessage: '密码须字母开头，6-32位字母和数字组合',
        error: false,
        disabled: false,
      }
    ],
    typeColumns: [{
      code: '1',
      text: '预定型'
    }, {
      code: '2',
      text: '预约型'
    }],
    openTimeChoice: [{
        values: ['08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', '18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', ],
        defaultIndex: 0
      },
      {
        values: ['18:00', '19:00', '20:00', '21:00', '22:00', '23:00', '00:00', '01:00', '02:00', '03:00', '04:00', '05:00', '06:00', '07:00', '08:00', '09:00', '10:00', '11:00', '12:00', '13:00', '14:00', '15:00', '16:00', '17:00', ],
        defaultIndex: 0
      },
    ],
    AddressColumns: [{
        values: [],
        className: '省',
      },
      {
        values: [],
        className: '市',
      },
      {
        values: [],
        className: '县',
      },
    ]
  },
  onTypeConfirm(e) {
    // console.log(e.detail)
    //1预定型2预约型
    this.setData({
      'choiceValues.shop_type': e.detail.value,
      [`fieldArr[4].value`]: e.detail.value.code,
      pickerTypeShow: false,
      [`fieldArr[4].error`]: false,
    })
    // console.log(this.data.fieldArr[4].value)
  },
  onClose() {
    this.setData({
      chooseAddress: false,
      pickerTypeShow: false,
      openTimeChoiceShow: false,
      chooseShopCate: false
    })
  },
  addressConfirm(e) {
    // console.log(e.detail)
    let str = e.detail.value[0].name + e.detail.value[1].name + e.detail.value[2].name
    this.setData({
      'choiceValues.addressInfo': e.detail,
      'choiceValues.addressTitle': str,
      [`fieldArr[5].value`]: str,
      [`fieldArr[5].error`]: false,
    })
    this.onClose();
  },

  fieldTap(e) {
    // console.log(e.currentTarget.dataset.value);
    let id = e.currentTarget.dataset.value;
    if (id == 2) {
      //弹出商家类型选项
      this.setData({
        pickerTypeShow: true
      })
    } else if (id == 3) {
      // console.log('aaa')
      //获取默认显示的省市县信息，请求完成前显示加载画面
      this.setData({
        addressLoading: true
      })
      util.sendRequest('get/province', 'GET').then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          let result = res.data.result;
          this.setData({
            [`AddressColumns[0].values`]: result,
            addressLoading: false,
          })
          var code1 = result[0].code
          util.sendRequest('get/city?code=' + code1, 'GET').then(res => {
            // console.log(res)
            if (res.data.code === 0) {
              let result = res.data.result;
              this.setData({
                [`AddressColumns[1].values`]: result,
              })
              var code2 = result[0].code;
              util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
                if (res.data.code === 0) {
                  let result = res.data.result;
                  this.setData({
                    [`AddressColumns[2].values`]: result,
                    addressLoading: false,
                  })
                }
              })
            }
          })
        }
      })

      //弹出联系地址选项
      this.setData({
        chooseAddress: true
      })
    } else if (id == 5) {
      //跳转到上传图片
      wx.navigateTo({
        url: '/pages/upImge/upImge',
      })
    } else if (id == 9) {
      //弹出营业时间选择器
      this.setData({
        openTimeChoiceShow: true
      })
    } else if (id == 11) {
      //获取商家分类，弹出选择
      this.setData({
        cateLoading: true,
        chooseShopCate: true,
      })
      util.sendRequest('shopcate/list', 'GET').then(res => {
        if (res.data.code === 0) {
          let result = res.data.result;
          console.log(result)
          this.setData({
            shopCateArr: result,
            cateLoading: false
          })
        }
      })
    } else if (id == 12) {
      //进入地址选择界面
      wx.getLocation({
        success: (res) => {
          // console.log(res)
          wx.chooseLocation({
            latitude: res.latitude,
            longitude: res.longitude,
            success: (res) => {
              // console.log(res);
              this.setData({
                'choiceValues.shopAddress': res,
                [`fieldArr[6].value`]: res.address,
                [`fieldArr[6].error`]: false
              })
            },
            fail: (res) => {
              wx.showToast({
                title: '选择地址失败,请稍后重试',
                icon: 'none'
              })
            },
          })
        }
      })
    }
  },
  onShopCateConfirm(e) {
    // console.log(e.detail.value);
    let value = e.detail.value;
    this.setData({
      'fieldArr[3].value': value.shop_cate_id,
      'choiceValues.shop_cate': value,
      chooseShopCate: false,
      [`fieldArr[3].error`]: false,
    })
    // console.log(this.data.fieldArr[3].value)
  },
  addressOnChoosen(e) {
    //选择地址时，根据选中的选项发送请求
    // console.log(e)
    var index = e.detail.index;
    var code = e.detail.value[index].code
    // console.log(index, code);
    if (index <= 1) {
      this.setData({
        'addressLoading': true
      })
      //当修改的是省级/市级选项时，需要刷新下级菜单
      //获取下级菜单
      let url = index === 0 ? ('get/city?code=' + code) : ('get/area?code=' + code)
      util.sendRequest(url, 'GET').then(res => {
        // console.log(res)
        if (res.data.code === 0) {
          let result = res.data.result
          this.setData({
            [`AddressColumns[${index+1}].values`]: result,
          })
          //修改的是省级菜单，那么还要获取再下一级菜单
          if (index === 0) {
            var code2 = result[0].code;
            // console.log(code2)
            util.sendRequest('get/area?code=' + code2, 'GET').then(res => {
              if (res.data.code === 0) {
                let result = res.data.result;
                this.setData({
                  [`AddressColumns[2].values`]: result,
                  addressLoading: false,
                })
              }
            })
          } else {
            this.setData({
              'addressLoading': false
            })
          }
        }
      })
    }
  },

  onOpenTimeConfirm(e) {
    // console.log(e)
    this.setData({
      'choiceValues.open_start_time': e.detail.value[0],
      'choiceValues.open_end_time': e.detail.value[1],
      [`fieldArr[9].value`]: e.detail.value,
      [`fieldArr[9].error`]: false,
      openTimeChoiceShow: false
    })
  },

  fieldBlur(e) {
    //field失去焦点时触发，修改数据值，判断是否有输入内容，没有提示错误，(选择不会触发这个问题)
    var index = e.currentTarget.dataset.index;
    var value = e.detail.value;
    // console.log(index, value)
    //如果修改后的值为空，那么提示错误
    var accountReg = getApp().globalData.accountReg;
    var passwordReg = getApp().globalData.passwordReg;
    if (value.length === 0) {
      this.setData({
        [`fieldArr[${index}].value`]: value,
        [`fieldArr[${index}].error`]: true
      })
    } else if (index === 11 || index === 12) {
      this.setData({
        [`fieldArr[${index}].error`]: !(index === 11 ? accountReg.test(value) : passwordReg.test(value)),
        [`fieldArr[${index}].value`]: value,
      })
      // console.log(index === 11 ? accountReg.test(value) : passwordReg.test(value))
    } else {
      this.setData({
        [`fieldArr[${index}].error`]: false,
        [`fieldArr[${index}].value`]: value,
      })
    }

  },
  apply() {
    //1. 判断内容是否有错， 无错那么请求服务器，
    var fieldArr = this.data.fieldArr
    var count = 0;
    var applyed = getApp().globalData.BusinessJoinImgApplyed
    // console.log(applyed)
    var accountReg = getApp().globalData.accountReg;
    var passwordReg = getApp().globalData.passwordReg;
    for (var i = 0; i < fieldArr.length; i++) {
      // console.log(i)
      // console.log(fieldArr[i].value)
      if (fieldArr[i].value.length === 0) {
        if (i == 7 && applyed) {
          this.setData({
            [`fieldArr[${i}].error`]: false
          })
        } else {
          this.setData({
            [`fieldArr[${i}].error`]: true
          })
          break;
        }
      } else if (i === 10) {
        if (accountReg.test(fieldArr[i].value)) {
          count++
          this.setData({
            [`fieldArr[${i}].error`]: false
          })
        } else {
          this.setData({
            [`fieldArr[${i}].error`]: true
          })
          break;
        }
      } else if (i === 11) {
        if (passwordReg.test(fieldArr[i].value)) {
          count++
          this.setData({
            [`fieldArr[${i}].error`]: false
          })
        } else {
          this.setData({
            [`fieldArr[${i}].error`]: true
          })
          break;
        }
      } else {
        count++
        this.setData({
          [`fieldArr[${i}].error`]: false
        })
      }
    }
    console.log(count)
    //2. 发送请求
    if (count === 11 && applyed) {
      var chooseInfo = this.data.choiceValues;
      // console.log(chooseInfo)
      var data = {}
      for (let item of fieldArr) {
        if (item.id !== 5 && item.id !== 9 && item.id !== 3) {
          data[`${item.dataName}`] = item.value;
        }
      }
      //将选择器选择的内容添加进data对象：
      data['province_code'] = chooseInfo.addressInfo.value[0].code;
      data['city_code'] = chooseInfo.addressInfo.value[1].code;
      data['area_code'] = chooseInfo.addressInfo.value[2].code;
      data['open_end_time'] = chooseInfo.open_end_time + ':00';
      data['open_start_time'] = chooseInfo.open_start_time + ':00';
      //添加店铺经纬度
      data['address_altitude'] = chooseInfo.shopAddress.latitude;
      data['address_latitude'] = chooseInfo.shopAddress.longitude;
      //获取图片信息：
      wx.getStorage({
        key: 'BusinessJoinImg',
        success: (res) => {
          // console.log(res.data)
          Object.assign(data, res.data);
          console.log(data)
          //发送请求：
          util.sendRequest('shop/enter', 'POST', data).then(res => {
            console.log(res)
            if (res.data.code === 0) {
              wx.showToast({
                title: '申请提交成功！',
                icon: 'none',
                success: () => {
                  //清除申请的图片缓存
                  wx.removeStorageSync('BusinessJoinImg');
                  wx.removeStorageSync('BusinessJoinMenuArr');
                  
                  wx.redirectTo({
                    url: '/pages/BusinessJoin/BusinessJoin',
                  })
                }
              })
            } else {
              wx.showToast({
                title: res.data.msg,
                icon: 'none',
              })
            }
          })
        },
        fail: (res) => {
          wx.showToast({
            title: '请上传图片',
            icon: 'none'
          })
        }
      })
    }
  },
  reApply() {
    //重新申请 修改状态为未申请
    this.setData({
      BussinessApplied: true
    })
  },

  successBtn() {
    wx.redirectTo({
      url: '/pages/ShopOwnerPages/login/login',
    })
  },

  getApplyStatus() {
    //获取申请状态，审核状态：1待审核2已通过3已驳回4后台移除
    util.sendRequest('shop/audit/sate', 'GET').then(res => {
      // console.log(res)
      if (res.data.code === 1) {
        this.setData({
          BussinessApplied: true
        })
      } else if (res.data.code === 0) {
        this.setData({
          applyStatus: res.data.result.audit_state,
          reject_reason: res.data.result.reject_reason
        })
      }
    })
  },

  onLoad: function (options) {
    this.getApplyStatus()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    if (getApp().globalData.BusinessJoinImgApplyed) {
      this.setData({
        imageApplyed: getApp().globalData.BusinessJoinImgApplyed
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})